package com.acwer.framework.data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.javassist.expr.NewArray;

import lombok.Data;


@Data
public class DataRow {

	private List<DataCell> cells = new ArrayList<DataCell>();

	//private Object model;

	private static Map<String, List<Field>> fieldCache=new HashMap<String, List<Field>>();
	
	public DataRow(Object model) {
		List<DataColumn> columns=DataColumnUtils.getColumnsByClzz(model.getClass());
		
		init(model,columns);

	}

	private void init(Object model,List<DataColumn> columns){
		//this.model = model;
		//System.out.println("model:"+model);
		//if(model==null) return;
		List<Field> fields=new ArrayList<Field>();
		String cacheKey=model.getClass().getName();
		//缓存model的字段信息
		if(fieldCache.containsKey(cacheKey)){
			fields=fieldCache.get(cacheKey);
		}else{
			fields = DataColumnUtils.getAllFields(model.getClass());
			fieldCache.put(cacheKey, fields);
		}
		

		for (DataColumn column : columns) {
			try {
				Field field = fields
						.stream()
						.filter(it -> it.getName().equals(
								column.getColumnName())).findFirst().get();

				// model.getClass().getDeclaredField(column.getColumnName());
				field.setAccessible(true);
				Object value = field.get(model);
				DataCell cell = new DataCell(column,value, 
						!StringUtils.isEmpty(column.getControlType())?
								column.getControlType():column.getStrDataType());
				cells.add(cell);
			} catch (Exception e) {

			}

		}
	}
	public DataRow(Object model, List<DataColumn> columns) {
		init(model, columns);
	}

	/**
	 * 通过字段名称获取单元格信息
	 * @param columnName
	 * @return
	 */
	public DataCell get(String columnName) {
//		Optional<DataCell> oCell = cells
//				.stream()
//				.filter(it -> it.getColumn().getColumnName().equals(columnName))
//				.findFirst();
//		return oCell.isPresent() ? oCell.get() : null;
		return null;
	}
	public List<DataCell> getCells() {
		return cells;
	}
}
